<?php

/**
 * Simple Google language api client
 *
 * http://code.google.com/p/googlelanguageapiphpclient/
 *
 * @author Yannis Rizos <yrizos@gmail.com>
 * @copyright Copyright (c) 2010, Yannis Rizos
 * @license http://opensource.org/licenses/gpl-3.0.html GNU General Public License, version 3 (GPLv3)
 * @version 1.0
 * @example example.php
 */
class GoogleLanguageAPIClient {

    /**
     * Google language api url
     * @staticvar string
     */
    public static $apiUrl = "http://ajax.googleapis.com/ajax/services/language/translate";

    /**
     * Google language api version
     * @staticvar string
     */
    public static $apiVersion = "1.0";

    /**
     * Constructor
     * @throws Exception
     */
    public function __construct() {
        if(!$this->checkDependencies()) {
            throw new Exception(__CLASS__ . " needs curl & json extensions");
        }
    }

    /**
     * Translates text
     *
     * @throws Exception
     * @param string $text
     * @param string $languageFrom $text language
     * @param string $languageTo language to translate to
     * @return string
     */
    public function translate($text, $languageFrom, $languageTo) {
        if(!$response = $this->getResponseCURL($this->getTranslationUrl($text, $languageFrom, $languageTo))) {
            throw new Exception("Network error");
        }

        $response = $this->decodeJSONResponce($response);        
        return $response["responseData"]["translatedText"];
    }

    /**
     * Gets translation url
     * @param string $text
     * @param string $languageFrom
     * @param string $languageTwo
     * @return string
     */
    public function getTranslationUrl($text, $languageFrom, $languageTo) {
        return
            self::$apiUrl
            . "?v=" . self::$apiVersion
            . "&q=" . rawurlencode($text)
            . "&langpair=" . rawurlencode($languageFrom) . "|" . rawurlencode($languageTo)
        ;
    }

    /**
     * Gets curl response
     * @param string $url
     * @return string|bool
     */
    private function getResponseCURL($url) {
        $curlOptions = array(
            CURLOPT_URL => $url,
            CURLOPT_REFERER => "http://{$_SERVER['HTTP_HOST']}/",
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FAILONERROR => 1,
            CURLOPT_CONNECTTIMEOUT => 30            
        );

        $curl = curl_init();
        curl_setopt_array($curl, $curlOptions);
        $response =@ curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    /**
     * Decodes curl response
     * @throws Exception
     * @param string $response
     * @return array
     */
    private function decodeJSONResponce($response) {
        $response = json_decode($response, true);
        if(empty($response)) {
            throw new Exception("Response decoding failed");
        }

        if(
            empty($response)
            || !isset($response["responseData"])
            || !isset($response["responseData"]["translatedText"])
            || !isset($response["responseStatus"])
            || $response["responseStatus"] !== 200
        ) {
            $status = "unknown";

            if(isset($response["responseStatus"])) {
                $status = $response["responseStatus"];
            }

            if(isset($response["responseDetails"])) {
                $status .= " [{$response["responseDetails"]}]";
            }

            throw new Exception("Response error status: {$status}");
        }

        return $response;
    }

    /**
     * Checks if curl & json are loaded
     * @return bool
     */
    private function checkDependencies() {
        return
            extension_loaded("curl")
            && extension_loaded("json");
    }
}

?>
